import apiService from '../../utils/api.js';

class CharacterCard {
  constructor(characterData, onSelect) {
    // 初始化默认头像
    if (!localStorage.getItem('default-avatar')) {
      const defaultAvatar = 'iVBORw0KGgoAAAANSUhEUgAA...'; // 添加默认base64头像数据
      localStorage.setItem('default-avatar', defaultAvatar);
    }

    this.characterData = characterData || {};
    this.onSelect = onSelect;
    this.card = null; // 延迟创建容器
    this.setupEventListeners();
  }


  setupEventListeners() {
    // 事件监听器将在render时设置
  }

  render() {
    // 创建新的容器，确保每个角色面板独立
    this.card = document.createElement('div');
    
    // 如果没有角色数据，返回空容器
    if (!this.characterData || Object.keys(this.characterData).length === 0) {
      this.card.classList.add('character-card', 'empty');
      return this.card;
    }
    this.card.classList.add('character-card');
    
    // 加载动画容器
    const loader = document.createElement('div');
    loader.classList.add('character-loader');
    loader.innerHTML = `
      <div class="loader-spinner"></div>
      <div class="loader-text">加载中...</div>
    `;
    this.card.appendChild(loader);

    // 角色内容容器
    const content = document.createElement('div');
    content.classList.add('character-content', 'hidden');
    
    // 角色头像
    const avatar = document.createElement('img');
    avatar.src = this.characterData.avatar || '';
    avatar.classList.add('character-avatar');
    avatar.onload = () => {
      this.card.classList.add('loaded');
      loader.classList.add('fade-out');
      content.classList.remove('hidden');
      setTimeout(() => {
        loader.remove();
      }, 300);
    };
    let retryCount = 0;
    avatar.onerror = () => {
      this.card.classList.add('loaded');
      if (retryCount < 1 && this.characterData.avatar) {
        retryCount++;
        avatar.src = this.characterData.avatar;
        return;
      }
      // 停止重试，显示默认头像
      if (retryCount < 2) {
        retryCount++;
        avatar.src = localStorage.getItem('default-avatar') || '';
        return;
      }
      // 最终处理
      avatar.src = '';
      loader.classList.add('fade-out');
      content.classList.remove('hidden');
      setTimeout(() => {
        loader.remove();
      }, 300);
      avatar.onerror = null; // 移除错误监听器
    };
    content.appendChild(avatar);

    // 角色名称
    const name = document.createElement('div');
    name.textContent = this.characterData.name;
    name.classList.add('character-name');
    content.appendChild(name);

    // 角色状态
    const status = document.createElement('div');
    status.textContent = this.characterData.status || '空闲';
    status.classList.add('character-status');
    content.appendChild(status);

    this.card.appendChild(content);
    
    // 添加点击事件监听
    this.card.addEventListener('click', () => {
      const dataToSend = {
        ...this.characterData,
        avatar: this.characterData.avatar
      };
      this.onSelect(dataToSend);
    });
    
    return this.card;
  }

  updateStatus(newStatus) {
    const statusElement = this.card.querySelector('.character-status');
    if (statusElement) {
      statusElement.textContent = newStatus;
    }
  }

  getData() {
    return {
      ...this.characterData,
      avatar: this.characterData.avatar || localStorage.getItem('default-avatar')
    };
  }

  update(characterData) {
    // 合并新数据和现有数据
    this.characterData = {
      ...this.characterData,
      ...characterData
    };
    
    const avatar = this.card.querySelector('.character-avatar');
    const name = this.card.querySelector('.character-name');
    const status = this.card.querySelector('.character-status');
    
    if (avatar) {
      // 如果是File对象，读取为Data URL
      if (characterData.avatar instanceof File) {
        const reader = new FileReader();
        reader.onload = (e) => {
          avatar.src = e.target.result;
          this.characterData.avatar = e.target.result; // 更新角色数据中的avatar
        };
        reader.readAsDataURL(characterData.avatar);
      } else {
        avatar.src = characterData.avatar || 'default-avatar.png';
        this.characterData.avatar = characterData.avatar || 'default-avatar.png'; // 更新角色数据中的avatar
      }
    }
    if (name) {
      name.textContent = characterData.name;
      this.characterData.name = characterData.name; // 更新角色数据中的name
    }
    if (status) {
      status.textContent = characterData.status || '空闲';
      this.characterData.status = characterData.status || '空闲'; // 更新角色数据中的status
    }
  }
}

export default CharacterCard;
